﻿using System.Collections;
using System.IO;
using System.Text;
using Puerts;
using Puerts.TSLoader;
using UnityEngine;
using XLua;

namespace Vasuleg
{
    public class MainApplication : MonoBehaviour
    {
        
        private JsEnv _jsEnv;
        private LuaEnv _luaEnv;

        private void Start()
        {
            Application.runInBackground = true;
            
            _jsEnv = CreateJsEnv();
            _luaEnv = CreateLuaEnv();
            
            _jsEnv.ExecuteModule("TSMainApplication.mts");
        }

        private static JsEnv CreateJsEnv()
        {
            var path = Path.Combine(Application.dataPath, "Scripts/TypsScript");
            var modulePath = Path.Combine(Application.dataPath, "..");
            var tsLoader = new TSLoader(new[] {path, modulePath});
            tsLoader.UseRuntimeLoader(new NodeModuleLoader(path));
            tsLoader.UseRuntimeLoader(new NodeModuleLoader(modulePath));
            tsLoader.UseRuntimeLoader(new DefaultLoader());
            return new JsEnv(tsLoader, 9229);
        }

        private static LuaEnv CreateLuaEnv()
        {
            var luaEnv = new LuaEnv();
            luaEnv.AddLoader(LuaCustomLoader);
            return luaEnv;
        }
        
        
        private void Update()
        {
            _jsEnv.Tick();
            _luaEnv.Tick();
        }

        private static byte[] LuaCustomLoader(ref string filepath)
        {
            var absPath = $"{Application.dataPath}/Scripts/Lua/{filepath}.lua";
            return File.Exists(absPath) ? Encoding.UTF8.GetBytes(File.ReadAllText(absPath)) : null;
        }

        public void OnDestroy()
        {
            _jsEnv.Dispose();
            _luaEnv.Dispose();
        }
    }
}